export default class HttpMgr {
	public static request(url: string, args?: any, isPost?: boolean, retJson?: boolean) {
		return new Promise<string|any>((resolve, reject) => {
			const xhr = cc.loader.getXMLHttpRequest();

			xhr.timeout = 10000;
			xhr.ontimeout = () => {
				reject('timeout! url:' + url + ' 请求超时');
			}
			xhr.onerror = () => {
				reject('error! url:' + url + ',statusText:' + xhr.statusText);
			};
			xhr.onreadystatechange = () => {
				if (xhr.readyState == 4) {
					if (xhr.status >= 200 && xhr.status < 400) {
						let res = xhr.responseText;
						if (retJson) {
							res = JSON.parse(res);
						}
						resolve(res);
					} else {
						reject('bad status! url:' + url + ',status:' + xhr.status + ',statusText:' + xhr.statusText);
					}
				}
			}

			var httpParams = this.dict2HttpParams(args);

			if (!isPost) {
				url = httpParams == '' ? url : url + '?' + httpParams;
				xhr.open("GET", url, true);
				xhr.send();
			} else {
				xhr.open("POST", url, true);
				xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
				xhr.send(httpParams);
			}
		});
	}


	public static request2(url: string, caller?: any, callback?: Function, args?: any, isPost?: boolean, retJson?: boolean): void {
		const xhr = new XMLHttpRequest();

		xhr.timeout = 10000;
		xhr.ontimeout = () => {
			this.doCallback(caller, callback, '请求超时');
		}
		xhr.onerror = () => {
			this.doCallback(caller, callback, 'error! url:' + url + ',statusText:' + xhr.statusText);
		};
		xhr.onreadystatechange = () => {
			if (xhr.readyState == 4) {
				if (xhr.status >= 200 && xhr.status < 400) {
					let res = xhr.responseText;
					if (retJson) {
						res = JSON.parse(res);
					}
					this.doCallback(caller, callback, '', res);
				} else {
					this.doCallback(caller, callback, '(error) readyState: ' + xhr.readyState + ' status: ' + xhr.status);
				}
			}
		}

		var httpParams = this.dict2HttpParams(args);

		if (!isPost) {
			url = httpParams == '' ? url : url + '?' + httpParams;
			xhr.open("GET", url, true);
			xhr.send();
		} else {
			xhr.open("POST", url, true);
			xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			xhr.send(httpParams);
		}
	}


	private static dict2HttpParams(dict: { [x: string]: string; }): string {
		if (!dict) return '';

		let content = '';
		for (const key in dict) content += key + '=' + dict[key] + '&';

		return content.substr(0, content.length - 1);
	}

	private static doCallback(caller?: any, callback?: Function, errMsg?: string, response?: any): void {
		if (caller) {
			callback.apply(caller, [errMsg, response]);
		} else {
			callback(errMsg, response);
		}
	}
}
